package com.basic.bio.chat.easy;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 单线程实现群聊，但是只能发一条消息
 * @Date: 2024-03-28 19:03
 * @Author: wz
 **/
public class Server {

    public static void main(String[] args) {
        List<Socket> socketList = new ArrayList<>();
        try {
            ServerSocket ss = new ServerSocket(8888);
            while (true){
                Socket socket = ss.accept();
                socketList.add(socket);

                InputStream is = socket.getInputStream();
                int len;
                byte[] buf = new byte[1024];
                String msg = null;
                while ((len = is.read(buf)) != -1){
                    msg = new String(buf,0,len);
                }
                System.out.println("收到客户端发来的消息："+msg);
                socket.shutdownInput();
                for (Socket s : socketList) {
                    if(s.equals(socket)){
                        continue;
                    }
                    OutputStream oos = s.getOutputStream();
                    oos.write(msg.getBytes());
                    oos.flush();
                    System.out.println("成功分发");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
